package com.flycent.hqhs.ui;

import java.lang.ref.WeakReference;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.flycent.hqhs.App;
import com.flycent.hqhs.R;
import com.flycent.hqhs.bean.MyMessage;
import com.flycent.hqhs.bean.PageEntity;
import com.flycent.hqhs.http.WebClient;
import com.flycent.hqhs.http.WebException;
import com.flycent.hqhs.ui.view.AbsViewHolderAdapter;
import com.flycent.hqhs.ui.view.DoubleButtonDialog;
import com.flycent.hqhs.ui.view.RefreshViewLoadMoreProxy;
import com.flycent.hqhs.ui.view.RefreshViewLoadMoreProxy.OnLoadDataActionListener;
import com.flycent.hqhs.ui.view.SimpleTitleBar;
import com.flycent.hqhs.util.DateTimeUtil;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

/**
 * @author fbl
 * 我的消息管理
 */
@SuppressLint("HandlerLeak") 
public class MessageManagementActivity extends BackableTitleBarActivity implements OnLoadDataActionListener,OnItemLongClickListener{

	PullToRefreshListView mRefreshListView;
	RefreshViewLoadMoreProxy mLoadMoreProxy;
	private MessageManageAdapter mAdapter;
	private int nowpage = 1;
	private List<MyMessage> myMessages;
	private RelativeLayout mEmptyRelat;
	private DoubleButtonDialog mDoubleDialog;
	private Handler mHandler;


	@Override
	protected void onCreate(Bundle savedInstance) {
		super.onCreate(savedInstance);
		setContentView(R.layout.activity_message_managerment);
		getTitleBar().setTitle(R.string.mine_note_message);
		
		mHandler = new MyHandler(this);
		
		mEmptyRelat = (RelativeLayout) findViewById(R.id.message_empty_relat);
		mRefreshListView = (PullToRefreshListView) findViewById(R.id.message_management_list);
		mRefreshListView.setEmptyView(mEmptyRelat);
		mRefreshListView.getRefreshableView().setSelector(new ColorDrawable(Color.TRANSPARENT));
		mRefreshListView.getRefreshableView().setOnItemLongClickListener(this);

		mAdapter = new MessageManageAdapter(this,R.layout.item_message_management);
		mRefreshListView.setAdapter(mAdapter);

		mLoadMoreProxy = new RefreshViewLoadMoreProxy(mRefreshListView, Mode.BOTH,0,0);
		mLoadMoreProxy.setOnLoadDataActionListener(this);
		mLoadMoreProxy.refreshing();


		mRefreshListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, final int position,
					long id) {
				if("is".equals(mAdapter.getData().get(position-1).getIsRead().toString()) ){
					return;
				}
				new Thread(){
					public void run() {
						try {
							PageEntity<MyMessage> entry = WebClient.getInstance(MessageManagementActivity.this).doHitMessage(mAdapter.getData().get(position-1).getId());
							myMessages = entry.getContent();
						} catch (WebException e) {
							if (WebException.TYPE_SERVER_RETURN_NULL.equals(e.getStatusCode())){
								myMessages = null;
							}
							else
								e.printStackTrace();
							}
						mHandler.sendEmptyMessage(2);
					};
				
				}.start();
			}
		});

	}

	@Override
	public void onRefresh(int page) {
		updateMessageList(1, true);
	}

	@Override
	public void onLoadMore(int page) {
		nowpage++;
		updateMessageList(nowpage, false);
	}

	private void updateMessageList(final int pageNum,final boolean isRefresh){
		//		mLoadMoreProxy.loadDataActionComplete(false);
		new Thread(){
			public void run() {
				try{
					WebClient client = WebClient.getInstance(MessageManagementActivity.this);

					PageEntity<MyMessage> entry = client.getMessageList(pageNum, 20, "", "asc");
					int totlePage = entry.getTotalPages();

					myMessages = entry.getContent();
					if(pageNum > totlePage){
						App.showShortToast(R.string.the_end_page);
						myMessages = null;
					}
				} catch (WebException e) {
					if (WebException.TYPE_SERVER_RETURN_NULL.equals(e.getStatusCode())){
						myMessages = null;
					}
					else
						e.printStackTrace();
				}

				if(isRefresh)
					mHandler.sendEmptyMessage(0);	
				else
					mHandler.sendEmptyMessage(1);
			};
		}.start();

		//		mLoadMoreProxy.loadDataActionComplete(true);
	}

	private class MyHandler extends Handler{
		private WeakReference<Activity> mActivity;
		
		private MyHandler(Activity activity){
			mActivity = new WeakReference<Activity>(activity);
		}
		@Override
		public void dispatchMessage(Message msg) {
			super.dispatchMessage(msg);
			if( mActivity.get() != null ){
				
				switch (msg.what) {
				case 0:
					mAdapter.update(myMessages);
					mRefreshListView.onRefreshComplete();
					break;
				case 1:
					mAdapter.append(myMessages);
					mRefreshListView.onRefreshComplete();
					break;
				case 2:
					mAdapter.update(myMessages);
					break;
				default:
					break;
				}
			}
		}
		
	}


	public class MessageManageAdapter extends AbsViewHolderAdapter<MyMessage>{

		public MessageManageAdapter(Context context, int layoutRes) {
			super(context, layoutRes);
		}

		@Override
		protected void bindData(int pos, MyMessage itemData) {
			TextView mtextTitle = getViewFromHolder(R.id.message_title);
			TextView mtextTime = getViewFromHolder(R.id.message_time);
			TextView mtextCount = getViewFromHolder(R.id.message_count);

			mtextTitle.setText(itemData.getTitle());
			mtextTime.setText(DateTimeUtil.getDateTime1(itemData.getCreateDate()));
			mtextCount.setText(itemData.getContent());

			if("is".equals(itemData.getIsRead().toString()) ){
				mtextTitle.setTextColor(getResources().getColor(R.color.gray));	
				mtextTime.setTextColor(getResources().getColor(R.color.gray));	
				mtextCount.setTextColor(getResources().getColor(R.color.gray));	
			}else if("no".equals(itemData.getIsRead().toString())){
				mtextTitle.setTextColor(getResources().getColor(R.color.black));	
				mtextTime.setTextColor(getResources().getColor(R.color.black));	
				mtextCount.setTextColor(getResources().getColor(R.color.black));
			}
		} 

	}

	@Override
	protected void onTitleBarCreated(SimpleTitleBar titleBar) {
		super.onTitleBarCreated(titleBar);
		//		titleBar.setRightButtonText(R.string.shopcar_remove);
		//		titleBar.setOnRightButtonClickListener(new OnClickListener() {
		//			@Override
		//			public void onClick(View view) {
		//				App.showShortToast("清空");
		//			}
		//		});

	}
	/** 显示删除登录框 */
	private void showDeleteDialog(final long ids) {
		dismissDeleteDialog();
		mDoubleDialog = new DoubleButtonDialog(this);
		mDoubleDialog.showDialog(getString(R.string.info_delete_message), new View.OnClickListener() {
			@Override
			public void onClick(View v) {

				new Thread(){
					public void run() {
						try {
							PageEntity<MyMessage> entry = WebClient.getInstance(MessageManagementActivity.this).deleteMessage(ids);
							myMessages = entry.getContent();
						} catch (WebException e) {
							if (WebException.TYPE_SERVER_RETURN_NULL.equals(e.getStatusCode())){
								myMessages = null;
							}
							else
								e.printStackTrace();
						}catch (Exception e) {
						}	
						mHandler.sendEmptyMessage(2);
					};
				}.start();

			}
		});

	}
	/** 取消dialog */
	private void dismissDeleteDialog() {

		if( mDoubleDialog != null && mDoubleDialog.isShowing() ) {
			mDoubleDialog.dismiss();
		}
		mDoubleDialog = null;

	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view, int position,
			long id) {
		showDeleteDialog(mAdapter.getData().get(position-1).getId());	
		return true;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		dismissDeleteDialog();
		mHandler.removeCallbacksAndMessages(null);
	}


}
